<%--
  Created by IntelliJ IDEA.
  User: hp
  Date: 2018/12/9
  Time: 19:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <jsp:include page="${pageContext.request.contextPath}/common/tag.jsp"/>
</head>
<script>
    $(function () {
        /*添加角色绑定*/
        $.post("${pageContext.request.contextPath}/role/query",function (data) {
            $.each(data,function (index,item) {
                /*分配的单选按钮*/
                $("#danxuan").append("<input type=\"radio\" name=\"role\" value=\""+item.rid+"\"><label >"+item.rname+"</label>\n" +
                    "                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

                $("#roleid").append("<option value=\""+item.rid+"\">"+item.rname+"</option>");
            })
        });

        $(".myfile").fileinput({
            language: 'zh',
            //uploadUrl: "/role/uploadFile",
            maxFileSize: 0, //文件的大小
            maxFileCount:1,//文件的数量
            showUpload:false, //是否显示上传按钮
            showRemove :false, //显示移除按钮
            showPreview :true, //是否显示预览
            allowedFileExtensions: ["jpg", "png", "gif","jpeg"],
            enctype: 'multipart/form-data', //二进制传递参数
            browseClass: "btn btn-primary", //按钮样式
            dropZoneEnabled : false,//是否显示拖拽区域，默认不写为true，但是会占用很大区域
            previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
            autoReplace : true
        }).on("fileuploaded", function (event, data, previewId, index){
            swal({title:"上传成功",text:"小手一抖就上传成功了！",type:"success"});
            $("[name='photo']").val("/image/"+data.response.url);
        });

        $.post("${pageContext.request.contextPath}/role/query",function (data) {
            $.each(data,function (index,item) {
                $("#role").append("<option value=\""+item.rid+"\">"+item.rname+"</option>");
            })
        });

        /*table表格*/
       $("#mytable").bootstrapTable({
           url : '${pageContext.request.contextPath}/system/mfQuery',
           toolbar : '#add #del',
           height : 510,  //表格高度
           pagination : true, //开启分页
           pageSize : 2, //每页显示的行数
           pageList:[2,4,8,16], //设置可供选择的页面数据条数
           pageNumber:1, //如果设置了分页，首页页码。
           sidePagination:'server',  //启用服务器端分页
           queryParams:function(params){
               var temp = {  //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                   limit: params.limit,  //页面大小
                   offset: params.offset, //页码
                   name:$("#username").val(),
                   roleid:$("#role").val()
               };
               return temp;
           },
           columns : [
               {checkbox:true,align:'center'},
               {field : 'id',title : '编号',align : 'center'},
               {field : 'userName',title : '用户名',align : 'center'},
               {title : '头像',align : 'center',
                   formatter : function (index,row,value) {
                       return "<img src=\""+row.touxiang+"\" width=\"70px;\" height=\"65px;\"/>"
                   }
               },
               {field:'rname',title:'角色',align:'center'},
               {field : 'remarks',title : '备注',align : 'center'},
               {title:'操作',align : 'center',
                   formatter: function (index,row,value) {
                       return  "<button onclick=\"fenpei("+row.roleid+","+row.id+")\"  class=\"btn btn-primary\">分配角色</button>&nbsp;&nbsp;&nbsp;";
                   }
               }
           ]
       }) ;

        <!--校验框架-->
        $('#addform').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                userName: {
                    message: '请输入用户名',
                    validators: {
                        notEmpty: {
                            message: '用户名不能为空！'
                        },
                        stringLength: {
                            min: 6,
                            max: 30,
                            message: '必须是6-30个字符'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9_\.]+$/,
                            message: '字母或者数字开头'
                        }
                    }
                },
                password: {
                    message: '请输入密码',
                    validators: {
                        notEmpty: {
                            message: '密码不能为空！'
                        },
                        stringLength : {
                            max : 12,
                            min : 6,
                            message : '字符长度6-12位'
                        }
                    }
                },
                password2 : {
                    message:'',
                    validators: {
                        notEmpty: {
                            message: '确认密码不能为空！'
                        },
                        identical:{
                            field: 'password',
                            message:'两次密码不一致'
                        },
                        stringLength : {
                            max : 12,
                            min : 6,
                            message : '字符长度6-12位'
                        }
                    }
                },
                touxiang: {
                    validators: {
                        notEmpty: {
                            message: '上传图片不能为空'
                        },
                        file: {
                            extension: 'png,jpg,jpeg',
                            type: 'image/png,image/jpg,image/jpeg',
                            message: '请重新选择图片'
                        }
                    }
                },
                roleid: {
                    message: '角色校验失败',
                    validators: {
                        notEmpty: {
                            message: '请选择角色！'
                        },
                        callback: {
                            message: '请选择角色',
                            callback: function(value, validator) {
                                if (value == 0) {
                                    return false;
                                } else {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        });
    });
</script>
<body style="padding: 0px 10px;overflow-y: hidden">
<div class="">
    <form class="form-inline" style="margin-top: 20px;text-align: right">
        <div class="form-group">
            <label style="font-size: 15px;">角色：</label>&nbsp;
            <select name="name" id="role" class="form-control">
                <option value="0">请选择</option>
            </select>
        </div> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <div class="form-group">
            <label for="username">用户名称：</label>&nbsp;
            <input type="text" class="form-control" id="username" placeholder="zhangsan" style="height: 40px;">
        </div>
        <button onclick="serch();" class="btn btn-primary btn-lg" type="button"><span class="glyphicon glyphicon-search">搜索</span></button>
    </form>
    <a id="add" class="btn btn-primary" data-toggle="modal" href="#addmodal">添加</a>
    <a id="del" class="btn btn-primary" onclick="plshanchu()">批量删除</a>
    <%--<input type="text" id="huozhi">--%>

    <table id="mytable"></table>



    <div class="modal fade" id="addmodal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">添加系统员</h4>
                </div>
                <div class="modal-body">
                    <form id="addform" action="" method="post" class="form-horizontal" role="form" enctype="multipart/form-data">
                        <input type="hidden" id="addxiu" value="1">
                        <div class="form-group">
                            <input type="hidden" id="id">
                            <label class="control-label col-sm-3">用户名：</label>
                            <div class="col-sm-9">
                                <input type="text" name="userName" class="form-control">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-3">密码：</label>
                            <div class="col-sm-9">
                                <input type="password" name="password" class="form-control">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-3">确认密码：</label>
                            <div class="col-sm-9">
                                <input type="password" name="password2" class="form-control">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-3">头像：</label>
                            <div class="col-md-9">
                                <input multiple type="file" name="touxiang" class="myfile" value="" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-3">备注：</label>
                            <div class="col-sm-9">
                                <textarea name="remarks" class="form-control"></textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-3">角色：</label>
                            <div class="col-sm-9">
                                <select id="roleid" name="roleid" class="form-control">
                                    <option value="0">请选择</option>
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" onclick="addUserInfo()" class="btn btn-primary">提交</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
</div>
<%--分配权限--%>
<input type="hidden" id="userid" value="${userinfo.id}">
<div class="modal fade" id="modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">分配权限</h4>
            </div>
            <div class="modal-body">
                <form action="" method="post" role="form">
                    <div class="form-group" id="danxuan">
                        <%--<input type="radio" name="role" id="super" value="1"><label for="super">超级管理员</label>
                        <input type="radio" name="role" id="dianzhang" value="2"><label for="dianzhang">店长</label>
                        <input type="radio" name="role" id="putong" value="3"><label for="putong">普通管理员</label>--%>
                    </div>
                    <input type="hidden" id="uid" value="">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="bcfenpei()">保存</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body>
<script>
    /*点击搜索*/
    function serch() {
        //返回表格的 Options。
        var opts = $("#mytable").bootstrapTable("getOptions") ;
        $("#mytable").bootstrapTable('refreshOptions',{pageNumber:1});
        var limit = opts.pageSize ;
        var offset = (opts.pageNumber-1) * limit;
        var username = $("#username").val() ;
        var role = $("#role").val();
        $.post("${pageContext.request.contextPath}/system/mfQuery",{'name':username,'roleid':role,'limit':limit,'offset':offset},function (data) {
            // var mydata = eval("("+data+")") ;
            //重新绑定表格数据
            $("#mytable").bootstrapTable('load',data) ;
        })
    };

    function addUserInfo() {
        var addxiu = $("#addxiu").val();
        if(addxiu==1){
            alert("添加");
            //启用较验
            $("#addform").data("bootstrapValidator").validate();
            //验证是否通过true/false
            var flag = $("#addform").data("bootstrapValidator").isValid() ;
            if(flag){
                //序列化表单
                var formStr=$("#addform").serialize();
                //处理表单控件的中文乱码
                params = decodeURIComponent(formStr,true);
                $.ajax({
                    type : 'post',
                    url : '${pageContext.request.contextPath}/system/addinfo',
                    data : new FormData($("#addform")[0]),
                    contentType: false, //必须false才会自动加上正确的Content-Type
                    processData: false,//必须false才会避开jQuery对 formdata 的默认处理XMLHttpRequest会对 formdata 进行正确的处理
                    success : function (data) {
                        //alert(data);
                        document.getElementById("addform").reset();
                        $("#addform").data('bootstrapValidator').resetForm();//清除当前验证的关键之处
                        /*隐藏对话框*/
                        $("#addmodal").modal('hide');
                        $("#mytable").bootstrapTable('load',data);
                        //提示增加成功
                        swal("提示信息", "增加成功!", "success");
                    }
                })
            }
        }else{
            alert("修改");
        }
    }
    
    function plshanchu() {
        var rows = $("#mytable").bootstrapTable("getSelections");
        /*console.log(rows);*/
        var ids = "";
        if(rows.length==0){
            //提示增加成功
            swal("提示信息", "请选择一条数据要删除的记录!", "error");
            return;
        }else{
            swal({
                title: "您确定要删除这条信息吗",
                text: "删除后将无法恢复，请谨慎操作！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "删除",
                closeOnConfirm: false
            },function () {
                $.each(rows,function () {
                    ids+=this.id+",";
                });
                $.ajax({
                    type:'post',
                    url: '${pageContext.request.contextPath}/userInfo/pldelete',
                    data : {"ids":ids},
                    success:function (data) {
                        //从新绑定表格
                        $("#mytable").bootstrapTable('load',data);
                        //提示增加成功
                        swal("提示信息", "批量删除成功!", "success");
                    }
                });
            });
        }
    }
    
    function fenpei(roleid,id) {
        var userid = $("#userid").val();
        if(userid == 1){
            $("#modal").modal('show');
            $("#uid").val(id);
                $.each($("[name='role']"),function () {
                var r = $(this).val();
                if(r == roleid){
                    $(this).attr("checked","checked");
                }
        });
        }else{
            swal("提示信息", "对不起您不是超级管理员不能分配!", "error");
        }

    }
    function bcfenpei() {
        var roleid = $("input[name='role']:checked").val();
        var bianhao = $("#uid").val();

        $.post("${pageContext.request.contextPath}/userInfo/updateRole",{"roleid":roleid,"id":bianhao},function (data) {
            $("#modal").modal("hide");
            $("#mytable").bootstrapTable('load',data);
            swal("提示信息", "分配成功!", "success");
        });
    }
   
</script>
</html>
